package com.zhupanlin.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhupanlin.exception.KaptchNotMatchException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: 自定义filter
 * @date 2024/12/16 21:22
 */

public class LoginKaptchaFilter extends UsernamePasswordAuthenticationFilter {

    private static final String FORM_KAPTCHA_KEY = "kaptcha";
    private String kaptchaParameter = FORM_KAPTCHA_KEY;

    public void setKaptchaParameter(String kaptchaParameter) {
        this.kaptchaParameter = kaptchaParameter;
    }

    public String getKaptchaParameter() {
        return kaptchaParameter;
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        if(!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported：" + request.getMethod());
        }
        try {
            // 1.获取请求验证码
            // 2.获取 session 中验证码
            // 3.获取用户名 和密码认证
            Map<String, String> userInfo = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            String kaptcha = userInfo.get(getKaptchaParameter());
            String username = userInfo.get(getUsernameParameter());
            String password = userInfo.get(getPasswordParameter());
            HttpSession session = request.getSession();
            String verifyCode = (String) session.getAttribute("kaptcha");
            if (!ObjectUtils.isEmpty(kaptcha) && !ObjectUtils.isEmpty(verifyCode) &&
                kaptcha.equalsIgnoreCase(verifyCode)) {
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
                setDetails(request, authRequest);
                return this.getAuthenticationManager().authenticate(authRequest);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        throw new KaptchNotMatchException("验证码不匹配");
    }
}
